<template>
  <div class="calendar-container">
    <div class="calendar-header">
      <div class="calendar-nav">
        <el-button-group>
          <el-button @click="changeMonth(-1)" icon="el-icon-arrow-left">上月</el-button>
          <el-button @click="currentDate = new Date()" type="primary">今天</el-button>
          <el-button @click="changeMonth(1)" icon="el-icon-arrow-right">下月</el-button>
        </el-button-group>
      </div>
      <div class="calendar-title">
        {{ currentYear }}年{{ currentMonth + 1 }}月
      </div>
      <div class="calendar-view-options">
        <el-radio-group v-model="calendarView" size="small">
          <el-radio-button label="month">月视图</el-radio-button>
          <el-radio-button label="week">周视图</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <div class="calendar-body">
      <!-- 月视图 -->
      <div v-if="calendarView === 'month'" class="month-view">
        <div class="weekdays">
          <div v-for="day in weekDays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="days">
          <div 
            v-for="(day, index) in calendarDays" 
            :key="index" 
            class="day"
            :class="{
              'other-month': day.otherMonth,
              'today': isToday(day.date),
              'has-projects': getProjectsForDay(day.date).length > 0
            }"
          >
            <div class="day-header">
              <span class="day-number">{{ day.day }}</span>
            </div>
            <div class="day-content">
              <div 
                v-for="project in getProjectsForDay(day.date).slice(0, 3)" 
                :key="project.id"
                class="calendar-project"
                :class="'status-' + project.status"
                @click="$emit('project-click', project)"
              >
                <div class="project-title">{{ project.name }}</div>
              </div>
              <div 
                v-if="getProjectsForDay(day.date).length > 3" 
                class="more-projects"
                @click="showMoreProjects(day.date)"
              >
                +{{ getProjectsForDay(day.date).length - 3 }} 更多
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 周视图 -->
      <div v-else-if="calendarView === 'week'" class="week-view">
        <div class="week-header">
          <div class="week-header-time"></div>
          <div 
            v-for="(day, index) in weekViewDays" 
            :key="index" 
            class="week-header-day"
            :class="{ 'today': isToday(day.date) }"
          >
            <div class="week-day-name">{{ weekDays[day.date.getDay()] }}</div>
            <div class="week-day-number">{{ day.day }}</div>
          </div>
        </div>
        <div class="week-body">
          <div class="week-times">
            <div v-for="hour in 24" :key="hour" class="week-time">
              {{ (hour - 1).toString().padStart(2, '0') }}:00
            </div>
          </div>
          <div class="week-grid">
            <div 
              v-for="(day, dayIndex) in weekViewDays" 
              :key="dayIndex" 
              class="week-day-column"
            >
              <div 
                v-for="hour in 24" 
                :key="hour" 
                class="week-hour-cell"
                :class="{ 'current-hour': isCurrentHour(day.date, hour - 1) }"
              >
                <div 
                  v-for="project in getProjectsForHour(day.date, hour - 1)" 
                  :key="project.id"
                  class="week-project"
                  :class="'status-' + project.status"
                  @click="$emit('project-click', project)"
                >
                  {{ project.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 更多项目弹窗 -->
    <el-dialog
      v-model="moreProjectsVisible"
      :title="moreProjectsDate ? formatDate(moreProjectsDate) + ' 的项目' : '项目列表'"
      width="500px"
    >
      <el-table :data="moreProjectsList" style="width: 100%">
        <el-table-column prop="name" label="项目名称"></el-table-column>
        <el-table-column prop="manager" label="负责人"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewMoreProject(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  projects: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['project-click'])

// 日历视图类型：月视图/周视图
const calendarView = ref('month')

// 当前日期
const currentDate = ref(new Date())

// 星期几
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 当前年份
const currentYear = computed(() => currentDate.value.getFullYear())

// 当前月份
const currentMonth = computed(() => currentDate.value.getMonth())

// 更多项目弹窗
const moreProjectsVisible = ref(false)
const moreProjectsDate = ref(null)
const moreProjectsList = ref([])

// 计算月视图的日期
const calendarDays = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  
  // 当月第一天
  const firstDay = new Date(year, month, 1)
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0)
  
  // 当月天数
  const daysInMonth = lastDay.getDate()
  
  // 当月第一天是星期几
  const firstDayOfWeek = firstDay.getDay()
  
  // 上个月的最后几天
  const prevMonthDays = []
  if (firstDayOfWeek > 0) {
    const prevMonth = month === 0 ? 11 : month - 1
    const prevMonthYear = month === 0 ? year - 1 : year
    const prevMonthLastDay = new Date(prevMonthYear, prevMonth + 1, 0).getDate()
    
    for (let i = 0; i < firstDayOfWeek; i++) {
      const day = prevMonthLastDay - firstDayOfWeek + i + 1
      prevMonthDays.push({
        day,
        date: new Date(prevMonthYear, prevMonth, day),
        otherMonth: true
      })
    }
  }
  
  // 当月的天
  const currentMonthDays = []
  for (let i = 1; i <= daysInMonth; i++) {
    currentMonthDays.push({
      day: i,
      date: new Date(year, month, i),
      otherMonth: false
    })
  }
  
  // 下个月的前几天
  const nextMonthDays = []
  const totalDaysDisplayed = prevMonthDays.length + currentMonthDays.length
  const remainingDays = 42 - totalDaysDisplayed // 6行7列 = 42天
  
  if (remainingDays > 0) {
    const nextMonth = month === 11 ? 0 : month + 1
    const nextMonthYear = month === 11 ? year + 1 : year
    
    for (let i = 1; i <= remainingDays; i++) {
      nextMonthDays.push({
        day: i,
        date: new Date(nextMonthYear, nextMonth, i),
        otherMonth: true
      })
    }
  }
  
  return [...prevMonthDays, ...currentMonthDays, ...nextMonthDays]
})

// 计算周视图的日期
const weekViewDays = computed(() => {
  const date = new Date(currentDate.value)
  const day = date.getDay()
  
  // 调整到本周的周日
  date.setDate(date.getDate() - day)
  
  const days = []
  for (let i = 0; i < 7; i++) {
    const currentDay = new Date(date)
    days.push({
      day: currentDay.getDate(),
      date: currentDay
    })
    date.setDate(date.getDate() + 1)
  }
  
  return days
})

// 切换月份
const changeMonth = (delta) => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + delta)
  currentDate.value = newDate
}

// 判断是否是今天
const isToday = (date) => {
  const today = new Date()
  return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear()
}

// 判断是否是当前小时
const isCurrentHour = (date, hour) => {
  if (!isToday(date)) return false
  
  const now = new Date()
  return now.getHours() === hour
}

// 获取某天的项目
const getProjectsForDay = (date) => {
  return props.projects.filter(project => {
    const startDate = new Date(project.startDate)
    const endDate = new Date(project.endDate)
    
    // 检查日期是否在项目的开始和结束日期之间
    return date >= startDate && date <= endDate
  })
}

// 获取某天某小时的项目
const getProjectsForHour = (date, hour) => {
  // 简化处理：只显示当天的项目，不考虑具体小时
  // 实际应用中可以根据项目的具体开始和结束时间进行过滤
  return getProjectsForDay(date)
}

// 显示更多项目
const showMoreProjects = (date) => {
  moreProjectsDate.value = date
  moreProjectsList.value = getProjectsForDay(date)
  moreProjectsVisible.value = true
}

// 查看更多项目中的项目
const viewMoreProject = (project) => {
  moreProjectsVisible.value = false
  emit('project-click', project)
}

// 格式化日期
const formatDate = (date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'in-progress': 'primary',
    'completed': 'success',
    'paused': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待启动',
    'in-progress': '进行中',
    'completed': '已完成',
    'paused': '已暂停'
  }
  return statusMap[status] || '未知状态'
}
</script>

<style scoped>
.calendar-container {
  width: 100%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.calendar-title {
  font-size: 20px;
  font-weight: bold;
}

/* 月视图样式 */
.month-view {
  padding: 10px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
  margin-bottom: 10px;
}

.weekday {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  gap: 5px;
  height: 700px;
}

.day {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
  min-height: 100px;
  display: flex;
  flex-direction: column;
}

.day.other-month {
  background-color: #f9f9f9;
  color: #c0c4cc;
}

.day.today {
  background-color: #ecf5ff;
}

.day.has-projects {
  border-color: #409EFF;
}

.day-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 5px;
}

.day-number {
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}

.today .day-number {
  background-color: #409EFF;
  color: white;
}

.day-content {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.calendar-project {
  padding: 3px 6px;
  border-radius: 3px;
  font-size: 12px;
  color: white;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.calendar-project.status-pending {
  background-color: #909399;
}

.calendar-project.status-in-progress {
  background-color: #409EFF;
}

.calendar-project.status-completed {
  background-color: #67C23A;
}

.calendar-project.status-paused {
  background-color: #E6A23C;
}

.more-projects {
  font-size: 12px;
  color: #409EFF;
  text-align: center;
  cursor: pointer;
  margin-top: 3px;
}

/* 周视图样式 */
.week-view {
  display: flex;
  flex-direction: column;
  height: 700px;
}

.week-header {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.week-header-time {
  width: 60px;
  border-right: 1px solid #ebeef5;
}

.week-header-day {
  flex: 1;
  text-align: center;
  padding: 10px;
  border-right: 1px solid #ebeef5;
}

.week-header-day.today {
  background-color: #ecf5ff;
}

.week-day-name {
  font-weight: bold;
}

.week-day-number {
  margin-top: 5px;
  font-size: 18px;
}

.week-body {
  display: flex;
  flex: 1;
  overflow-y: auto;
}

.week-times {
  width: 60px;
  border-right: 1px solid #ebeef5;
}

.week-time {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
}

.week-grid {
  display: flex;
  flex: 1;
}

.week-day-column {
  flex: 1;
  border-right: 1px solid #ebeef5;
}

.week-hour-cell {
  height: 60px;
  border-bottom: 1px solid #ebeef5;
  padding: 2px;
  overflow-y: auto;
}

.week-hour-cell.current-hour {
  background-color: rgba(64, 158, 255, 0.1);
}

.week-project {
  margin: 2px 0;
  padding: 3px 6px;
  border-radius: 3px;
  font-size: 12px;
  color: white;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.week-project.status-pending {
  background-color: #909399;
}

.week-project.status-in-progress {
  background-color: #409EFF;
}

.week-project.status-completed {
  background-color: #67C23A;
}

.week-project.status-paused {
  background-color: #E6A23C;
}
</style> 